package cn.neusoft.service.impl;


import cn.neusoft.mapper.EmployeeMapper;
import cn.neusoft.pojo.Employee;
import cn.neusoft.query.BaseQuery;
import cn.neusoft.query.EmployeeQuery;
import cn.neusoft.service.IBaseService;

import cn.neusoft.service.IEmployeeService;
import cn.neusoft.vo.PageBean;
import cn.neusoft.vo.ResultBean;
import com.alibaba.druid.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class EmployeeService implements IEmployeeService {
	@Autowired
	private EmployeeMapper employeeMapper;
	@Override
	@Transactional
	public ResultBean add(Employee employee) throws Exception {
		if(employee==null|| StringUtils.isEmpty(employee.getEname())) {
			return ResultBean.ERROR("请求参数为空");
		}
		int add = employeeMapper.add(employee);
		System.out.println("添加了："+add+"条参数");
		return ResultBean.SUCCESS(employee.getEmpno());
	}

	@Override
	@Transactional
	public ResultBean update(Employee employee) throws Exception {
		if (employee == null || StringUtils.isEmpty(employee.getEname())
		|| employee.getEmpno()==null || employee.getEmpno()==0) {
			return ResultBean.ERROR("请求参数为空");
		}
		int add = employeeMapper.update(employee);
		System.out.println("修改了：" + add + "条参数");
		return ResultBean.SUCCESS();
	}

	@Override
	@Transactional
	public ResultBean delete(Integer id) throws Exception {
		if (id==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		int delete = employeeMapper.delete(id);
		System.out.println("修改了：" + delete + "条参数");
		return ResultBean.SUCCESS();
	}

	@Override
	@Transactional(readOnly = true)
	public ResultBean getById(Integer id) throws Exception {
		if(id==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		Employee employee =employeeMapper.getById(id);
		return ResultBean.SUCCESS(employee);
	}

	@Override
	@Transactional(readOnly = true)
	public ResultBean getAll() throws Exception {
		List<Employee> list=employeeMapper.getAll();
		return ResultBean.SUCCESS(list);
	}

	@Override
	@Transactional(readOnly = true)
	public ResultBean getByPage(BaseQuery baseQuery) throws Exception {
		PageBean<Employee> pageBean=new PageBean<>();
		//这里的意思是如果basequery为空的话，还可以让他继续查询
		if(baseQuery==null) {
			baseQuery=new BaseQuery();
		}
		int count= employeeMapper.getCount(baseQuery);
		pageBean.setTotalPages(count);
		List<Employee> list=employeeMapper.getByPage(baseQuery);
		pageBean.setData(list);
		return ResultBean.SUCCESS(pageBean);
	}

	@Override
	@Transactional
	public ResultBean batchDel(List<Integer> ids) throws Exception {
		if(ids==null) {
			return ResultBean.ERROR("请求参数为空");
		}
		for (Integer id:ids) {
			int delete = employeeMapper.delete(id);
			if(delete==0) {
				System.out.println("删除失败");
				//一般这里就要进行事务回滚
				//保证正确性
				return ResultBean.ERROR("删除失败,请检查代码问题");
			}
		}
		return ResultBean.SUCCESS();
	}
}
